/*
 * Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hazelcast.huaweicloud;

import com.hazelcast.internal.util.StringUtil;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.spi.utils.RetryUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Responsible for fetching discovery information from ECS API
 **/
public class HwClient {

    private static final ILogger LOGGER = Logger.getLogger(HwClient.class);
    private static final int RETRY = 2;
    private final HwApi hwApi;
    private final HwMetadataApi hwMetadataApi;
    private final HwAuthenticator hwAuthenticator;
    private final HwConfig hwConfig;
    private final List<Tag> tag;
    private final String projectId;
    private final String serverId;
    private final String zone;

    HwClient(HwApi hwApi, HwMetadataApi hwMetadataApi, HwAuthenticator hwAuthenticator, HwConfig hwConfig) {
        this.hwApi = hwApi;
        this.hwMetadataApi = hwMetadataApi;
        this.hwAuthenticator = hwAuthenticator;
        this.hwConfig = hwConfig;
        this.tag = hwConfig.getTags();

        this.zone = zoneFromConfigOrMetadata();
        this.projectId = projectIdFromConfigOrMetadata();
        this.serverId = serverIdFromConfigOrMetadata();
    }

    private String zoneFromConfigOrMetadata() {
        if (!StringUtil.isNullOrEmptyAfterTrim(hwConfig.getRegion())) {
            return hwConfig.getRegion();
        }

        return RetryUtils.retry(hwMetadataApi::getRegionId, RETRY);
    }

    private String projectIdFromConfigOrMetadata() {
        if (!StringUtil.isNullOrEmptyAfterTrim(hwConfig.getProjectId())) {
            return hwConfig.getProjectId();
        }

        return RetryUtils.retry(hwMetadataApi::getProjectId, RETRY);
    }

    private String serverIdFromConfigOrMetadata() {
        if (!StringUtil.isNullOrEmptyAfterTrim(hwConfig.getInstanceId())) {
            return hwConfig.getInstanceId();
        }

        return RetryUtils.retry(hwMetadataApi::getInstanceId, RETRY);
    }

    /**
     * If the user has set ak and sk, then priority should be given to using ak and
     * sk for identity authentication.
     * Otherwise, obtain a token through IAM authentication
     *
     * @return ip map
     */
    Map<String, String> getAddresses() {
        Map<String, String> tokenMap;
        // put ak and sk by EcsConfig
        if (!StringUtil.isNullOrEmptyAfterTrim(hwConfig.getAccessKey())) {
            tokenMap = new HashMap<>();
            tokenMap.put("accessKey", hwConfig.getAccessKey());
            tokenMap.put("secretKey", hwConfig.getSecretKey());
        } else {
            // put accessToken by Iam or metadata
            tokenMap = fetchAccessToken();
        }
        tokenMap.put("zone", zone);
        tokenMap.put("projectId", projectId);
        tokenMap.put("serverId", serverId);

        return hwApi.describeInstances(tokenMap, tag);
    }

    private Map<String, String> fetchAccessToken() {
        // from metadata
        if (hwConfig.isInstanceMetadataAvailable()) {
            LOGGER.fine("get token from metadata");
            return hwMetadataApi.accessToken();
        } else {
            // from iam
            HashMap<String, String> tokenMap = new HashMap<>();
            LOGGER.fine("get token from iam");
            tokenMap.put("token", hwAuthenticator.refreshAccessToken(hwConfig.getIamDomain(), hwConfig.getIamUser(),
                    hwConfig.getIamPassword(), projectId));
            return tokenMap;
        }
    }

    public String getAvailabilityZone() {
        return hwMetadataApi.getAvailabilityZone();
    }
}
